import { EntityManager, MikroORM } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Controller, Get, Inject, Param, Post, Query, Req } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { JsonApiResponse } from '@utils/json.api.response';
import { TokenService } from '../service/token.service';
import { Users } from "@entities/Users";
import { knexPrefix, prefix } from "@databases/vo/dao-helper";
import { UserskVO } from "@databases/vo/UserVO";
import { knext } from 'knext';
import dayjs from 'dayjs';
import MiniProgram from 'node-easywechat/dist/MiniProgram/Application';
import { Accounts } from '@databases/entities/Accounts';

@ApiTags('(站点) 账户')
@Controller('account')
export class AccountController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager,
        @Inject(TokenService)
        private readonly tokenService : TokenService
    ){}

    @Get('login/:id')
    async loginById(@Req() request, @Param('id') user_id) {

        const user = await this.em.getRepository(Users).findOne({'id': user_id},{
            fields: [
                ...prefix('',UserskVO.baseInfo())
            ]
        });

        if(!user)
        {
            return JsonApiResponse.ERR('账号或密码不正确.')
        }

        const token = await this.tokenService.createToken(user);

        return JsonApiResponse.new({token,user});
    }

    @Get('create')
    async create()
    {
        const knex = knext(this)

        const result = await knex.fromORM(Users).findOrCreate(
            [...knexPrefix(UserskVO.baseInfo())],
            {id:5},
            {created_at:dayjs().format(),updated_at:dayjs().format(),email:'beckham996@qq.com',roles:[],modules:[]}
        )

        // const result  = await knex.fromORM(Users)
        // .insert([
        //     {created_at:dayjs().format(),updated_at:dayjs().format(),email:'beckham996@qq.com' },
        // ])
        // .onConflict([
        //     'id'
        // ])
        // .ignore()

        return result
    }

    @Get('wxLogin')
    async wxLogin(@Query('code') code) {

        const app = new MiniProgram({
            // 配置项
            'app_id' : 'wx7075f04edc923e5b',
            'secret' : '6de604c134d247e678fecbd9b7d814af'
        })

        const session = await app.auth.session(code)

        //app.app_code.getQrCode('/pages')

        const knex = knext(this)

        // const account = await knex.fromORM(Accounts).findOrCreate(
        //     ['*'],
        //     {
        //         'openid' : session.openid,
        //     },
        //     {
        //         'account_type': 'wx-mini',
        //         'openid' : session.openid,
        //         'session_key' : session.session_key,
        //         'unionid' : session.unionid
        //     }
        // )

        let user : any = null
        await knex.transaction(async trx=>{
            await knex.fromORM(Accounts)
            .transacting(trx)
            .where({
                'openid' : session.openid
            })
            .then(async accounts => {
                if(accounts.length > 0) 
                {
                    user =  await knex.fromORM(Users)
                    .first([...knexPrefix(UserskVO.baseInfo())])
                    .where({id:accounts[0].user_id})
                    .then()
                    
                    return accounts
                }else{

                    await knex.fromORM(Users)
                    .insert({
                        roles:"[]",
                        modules:"[]",
                        created_at:dayjs().format('YYYY-MM-DD HH:mm:ss'),
                        updated_at:dayjs().format('YYYY-MM-DD HH:mm:ss'),
                        nickname : '微信用户',
                        head_icon_url : ''
                    }).then(async users => {
                        if(users[0] > 0)
                        {
                            await knex.fromORM(Accounts)
                            .insert({
                                    'created_at':dayjs().format('YYYY-MM-DD HH:mm:ss'),
                                    'updated_at':dayjs().format('YYYY-MM-DD HH:mm:ss'),
                                    'account_type': 'wx-mini',
                                    'openid' : session.openid,
                                    'session_key' : session.session_key,
                                    'unionid' : session.unionid,
                                    'user_id' : users[0]
                                },
                                ['*']
                            )
                            .then(async ()=>{
                                user = await knex.fromORM(Users)
                                .first([...knexPrefix(UserskVO.baseInfo())])
                                .where('id',users[0])
                                .then()
                            })
                        }
                    })

                    return null
                }
            })
            .then(trx.commit)
            .catch(trx.rollback)
        })

        const token = await this.tokenService.createToken(user);

        return JsonApiResponse.new({token,user});
    }
}
